package com.ycxy.springsecuritycourse.utils;

import com.ycxy.springsecuritycourse.entity.Users;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtil {
    private static final Logger log = LoggerFactory.getLogger(JwtTokenUtil.class);
    public static final String TOKEN_HEADER = "x-access-token"; //token请求头
    public static final String TOKEN_PREFIX = "Bearer";//token前缀
    private static final String ISSUER = "STC"; //发行方
    private static final String SUBJECT = "OMM"; //签名主题
    private static final String AUDIENCE = "OMM-VUE"; //接收方
    private String ROLE_CLAIMS = "role"; //角色权限声明
    private String secret = "secret"; //jwt加解密使用的密钥;
    private int expiration = 360; //jwt过期时间 秒级别

    private static final String CLAIM_KEY_ID= "id";//登录的用户编号
    private static final String CLAIM_KEY_CREATED = "created";// jwt创建时间


    /**
     * 生成token的过期时间
     */
    private Date generateExpirationDate() {
        //毫秒级
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 根据用户信息生成token
     */
    public String generateToken(Users user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_ID, user.getId());//用户名
        claims.put(CLAIM_KEY_CREATED, new Date());//创建日期

        return Jwts.builder()
                .setIssuer(ISSUER)//发行方
                .setSubject(SUBJECT)//主题
                .setAudience(AUDIENCE)//接收方
                .setClaims(claims)//其他信息，主要是用户信息
                .setIssuedAt(new Date())//签发日期
                .setNotBefore(new Date())//生效日期
                .setExpiration(generateExpirationDate())//失效时间
                .signWith(SignatureAlgorithm.HS512, secret)//生成算法
                .compact();
    }

    /**
     * 从token中获取JWT中的有效载荷
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            // 捕获过期异常
            log.info("token：" + token);
            log.info("token已经过期：" + e.getMessage());
            claims = e.getClaims();
        } catch (Exception e) {
            log.info("token：" + token);
            log.info("JWT格式验证失败：" + e.getMessage());
        }
        return claims;
    }

    /**
     * 从token中获取登录用户名
     */
    public String getIdFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.get(CLAIM_KEY_ID).toString();
    }

    /**
     * 从token中获取过期时间
     */
    public Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }


    /**
     * 判断token是否已经失效
     */
    public boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }
}
